<template>
  <div>
    <el-row>
      <el-button type="danger" @click="batchDelete()">批量删除</el-button>
    </el-row>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      :show-checkbox="true"
      node-key="catId"
      :default-expanded-keys="expanded"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            v-if="node.level <= 2"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            edit
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="node.childNodes.length == 0"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <!-- <el-input v-model="category.icon" autocomplete="off"></el-input> -->
          <single-upload v-model="category.icon"></single-upload>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SingleUpload from "@/components/upload/singleUpload"
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
export default {
  components: {SingleUpload},
  props: {},
  // 定义属性
  data() {
    return {
      dialogType: "", //新增：add，编辑：edit
      title: "", //弹窗名称
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
        catId: null,
      },
      dialogVisible: false,
      menus: [],
      expanded: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    batchDelete() {
      var catIds = [];
      var checkNode = this.$refs.menuTree.getCheckedNodes();
      for (let i = 0; i < checkNode.length; i++) {
        catIds.push(checkNode[i].catId);
      }

      this.$confirm(`是否删除【${catIds}}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新出新菜单
            this.getMeus();
            //设置需要默认展开的菜单
            this.expanded = [node.parent.data.catId];
          });
        })
        .catch(() => {});
    },

    //确定
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },

    //添加分类
    addCategory() {
      console.log("提交三级分类数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        console.log("保存成功后返回数据", data);
        this.$message({
          type: "success",
          message: "保存成功!",
        });

        //关闭对话框
        this.dialogVisible = false;

        //刷新数据
        this.getMeus();

        //设置默认展开菜单
        this.expanded = [this.category.parentCid];
      });
    },

    //编辑方法
    editCategory() {
      var { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        console.log("保存成功后返回数据", data);
        this.$message({
          type: "success",
          message: "修改成功!",
        });

        //关闭对话框
        this.dialogVisible = false;

        //刷新数据
        this.getMeus();

        //设置默认展开菜单
        this.expanded = [this.category.parentCid];
      });
    },

    //获取菜单（三级分类）数据
    getMeus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("三级分类数据：", data.data);
        this.menus = data.data;
      });
    },

    //添加节点
    append(data) {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.title = "添加分类";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.name = "";
      this.category.showStatus = 1;
      this.category.sort = 0;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.catId = "";
      console.log("添加节点信息：", data);
    },

    //编辑节点
    edit(data) {
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.title = "编辑分类";

      //及时获取数据库信息，防止其他人修改后，获取到的仍是旧数据（进入页面刷新过数据后就没再刷新了）
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },

    //删除节点
    remove(node, data) {
      var ids = [node.data.catId];

      this.$confirm(`是否删除【${node.data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新出新菜单
            this.getMeus();
            //设置需要默认展开的菜单
            this.expanded = [node.parent.data.catId];
          });
        })
        .catch(() => {});

      console.log("删除的节点信息：", node, data);
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMeus();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 页面激活就会执行，如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style scoped>
</style>